"""
性能优化协调器
基于测试结果协调所有性能优化组件，实现系统级优化
"""
import asyncio
import logging
import time
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from enum import Enum
import statistics
import numpy as np

from services.infrastructure.adaptive_performance_controller import adaptive_performance_controller
from services.infrastructure.multi_level_cache import multi_level_cache
from services.ai_infrastructure.gpu_resource_manager import gpu_resource_manager
from services.monitoring.database_performance_optimizer import database_optimizer
from services.monitoring.real_time_logging_service import logging_service
from services.monitoring.real_time_performance_monitor import performance_monitor
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


class OptimizationPriority(Enum):
    """优化优先级"""
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"


@dataclass
class SystemOptimizationResult:
    """系统优化结果"""
    optimization_id: str
    optimization_type: str
    priority: OptimizationPriority
    description: str
    performance_improvement: float
    resource_savings: Dict[str, Any]
    actions_taken: List[str]
    before_metrics: Dict[str, Any]
    after_metrics: Dict[str, Any]
    execution_time_ms: float
    timestamp: datetime = field(default_factory=datetime.now)
    success: bool = True
    error_message: Optional[str] = None


@dataclass
class OptimizationStrategy:
    """优化策略"""
    strategy_name: str
    target_components: List[str]
    trigger_conditions: Dict[str, Any]
    optimization_actions: List[str]
    expected_improvement: float
    priority: OptimizationPriority


class PerformanceOptimizationCoordinator:
    """性能优化协调器"""
    
    def __init__(self):
        # 优化组件引用
        self.adaptive_controller = adaptive_performance_controller
        self.cache_manager = multi_level_cache
        self.gpu_manager = gpu_resource_manager
        self.db_optimizer = database_optimizer
        self.logger = logging_service
        self.monitor = performance_monitor
        
        # 优化历史和统计
        self.optimization_history: List[SystemOptimizationResult] = []
        self.optimization_stats = {
            'total_optimizations': 0,
            'successful_optimizations': 0,
            'failed_optimizations': 0,
            'total_performance_improvement': 0.0,
            'avg_optimization_time': 0.0,
            'last_optimization_time': None
        }
        
        # 优化策略配置
        self.optimization_strategies = self._initialize_optimization_strategies()
        
        # 系统状态监控
        self.system_health_score = 100.0
        self.performance_trends = {
            'cpu_trend': [],
            'memory_trend': [],
            'gpu_trend': [],
            'latency_trend': [],
            'throughput_trend': []
        }
        
        # 优化配置
        self.optimization_config = {
            'auto_optimization_enabled': True,
            'optimization_interval_seconds': 300,  # 5分钟
            'critical_threshold': 90.0,  # 临界阈值
            'warning_threshold': 80.0,   # 警告阈值
            'min_improvement_threshold': 5.0,  # 最小改善阈值
            'max_concurrent_optimizations': 3,
            'optimization_cooldown_seconds': 60
        }
        
        # 运行状态
        self.is_running = False
        self.active_optimizations = {}
        self.last_optimization_time = datetime.now()
        
        # 监控任务
        self._coordination_task = None
        self._health_monitoring_task = None
        self._trend_analysis_task = None
    
    async def initialize(self):
        """初始化性能优化协调器"""
        try:
            # 初始化所有优化组件
            await self._initialize_optimization_components()
            
            # 启动协调任务
            self.is_running = True
            self._coordination_task = asyncio.create_task(self._coordination_loop())
            self._health_monitoring_task = asyncio.create_task(self._health_monitoring_loop())
            self._trend_analysis_task = asyncio.create_task(self._trend_analysis_loop())
            
            await self.logger.log_info("optimization_coordinator", "性能优化协调器已启动")
            logger.info("Performance Optimization Coordinator initialized")
            
        except Exception as e:
            logger.error(f"Failed to initialize Performance Optimization Coordinator: {e}")
            raise
    
    async def _initialize_optimization_components(self):
        """初始化优化组件"""
        try:
            # 确保所有组件都已初始化
            if not hasattr(self.adaptive_controller, '_monitoring_task'):
                await self.adaptive_controller.initialize()
            
            if not hasattr(self.cache_manager, '_monitoring_task'):
                await self.cache_manager.initialize()
            
            if not hasattr(self.db_optimizer, '_monitoring_task'):
                await self.db_optimizer.initialize()
            
            if not self.logger.is_running:
                await self.logger.start_service()
            
            if not self.monitor.is_monitoring:
                await self.monitor.start_monitoring()
            
            logger.info("All optimization components initialized")
            
        except Exception as e:
            logger.error(f"Failed to initialize optimization components: {e}")
            raise
    
    def _initialize_optimization_strategies(self) -> List[OptimizationStrategy]:
        """初始化优化策略"""
        strategies = [
            OptimizationStrategy(
                strategy_name="critical_resource_optimization",
                target_components=["adaptive_controller", "gpu_manager"],
                trigger_conditions={
                    "cpu_usage": 95.0,
                    "memory_usage": 90.0,
                    "gpu_usage": 95.0
                },
                optimization_actions=[
                    "reduce_concurrent_streams",
                    "pause_low_priority_tasks",
                    "optimize_gpu_allocation"
                ],
                expected_improvement=25.0,
                priority=OptimizationPriority.CRITICAL
            ),
            OptimizationStrategy(
                strategy_name="cache_performance_optimization",
                target_components=["cache_manager"],
                trigger_conditions={
                    "cache_hit_rate": 0.6,
                    "memory_usage": 85.0
                },
                optimization_actions=[
                    "optimize_cache_patterns",
                    "cleanup_expired_cache",
                    "adjust_cache_sizes"
                ],
                expected_improvement=15.0,
                priority=OptimizationPriority.HIGH
            ),
            OptimizationStrategy(
                strategy_name="database_performance_optimization",
                target_components=["db_optimizer"],
                trigger_conditions={
                    "slow_query_ratio": 0.1,
                    "avg_query_time": 1000.0
                },
                optimization_actions=[
                    "optimize_indexes",
                    "enable_batch_writes",
                    "cleanup_query_cache"
                ],
                expected_improvement=20.0,
                priority=OptimizationPriority.HIGH
            ),
            OptimizationStrategy(
                strategy_name="gpu_load_balancing",
                target_components=["gpu_manager"],
                trigger_conditions={
                    "gpu_load_imbalance": 0.4,
                    "gpu_memory_fragmentation": 0.3
                },
                optimization_actions=[
                    "rebalance_gpu_pools",
                    "defragment_gpu_memory",
                    "optimize_task_distribution"
                ],
                expected_improvement=18.0,
                priority=OptimizationPriority.MEDIUM
            ),
            OptimizationStrategy(
                strategy_name="adaptive_performance_tuning",
                target_components=["adaptive_controller"],
                trigger_conditions={
                    "response_time": 3000.0,
                    "queue_length": 50
                },
                optimization_actions=[
                    "adjust_frame_rates",
                    "optimize_batch_sizes",
                    "tune_processing_timeouts"
                ],
                expected_improvement=12.0,
                priority=OptimizationPriority.MEDIUM
            )
        ]
        
        return strategies
    
    async def execute_comprehensive_optimization(self) -> SystemOptimizationResult:
        """执行综合性能优化"""
        optimization_id = f"comprehensive_{int(time.time())}"
        start_time = time.time()
        
        try:
            await self.logger.log_info("optimization_coordinator", 
                                     f"开始执行综合性能优化 - ID: {optimization_id}")
            
            # 收集优化前的系统指标
            before_metrics = await self._collect_system_metrics()
            
            # 执行各组件优化
            optimization_results = []
            total_improvement = 0.0
            all_actions = []
            
            # 1. 自适应性能控制优化
            try:
                adaptive_result = await self.adaptive_controller.optimize_resource_allocation()
                if adaptive_result['actions_taken']:
                    optimization_results.append(("adaptive_controller", adaptive_result))
                    total_improvement += adaptive_result.get('performance_improvement', 0)
                    all_actions.extend([f"自适应控制: {action['action']}" for action in adaptive_result['actions_taken']])
            except Exception as e:
                logger.error(f"Adaptive controller optimization failed: {e}")
            
            # 2. 缓存系统优化
            try:
                cache_result = await self.cache_manager.optimize_cache()
                if cache_result['optimization_actions']:
                    optimization_results.append(("cache_manager", cache_result))
                    total_improvement += cache_result.get('performance_improvement', 0)
                    all_actions.extend([f"缓存优化: {action['action']}" for action in cache_result['optimization_actions']])
            except Exception as e:
                logger.error(f"Cache optimization failed: {e}")
            
            # 3. GPU资源优化
            try:
                gpu_suggestions = await self.gpu_manager.optimize_gpu_allocation()
                if gpu_suggestions:
                    gpu_result = await self._execute_gpu_optimizations(gpu_suggestions)
                    optimization_results.append(("gpu_manager", gpu_result))
                    total_improvement += gpu_result.get('performance_improvement', 0)
                    all_actions.extend([f"GPU优化: {action}" for action in gpu_result.get('actions_taken', [])])
            except Exception as e:
                logger.error(f"GPU optimization failed: {e}")
            
            # 4. 数据库性能优化
            try:
                db_result = await self.db_optimizer.optimize_database_indexes()
                if db_result.actions_taken:
                    optimization_results.append(("db_optimizer", db_result.__dict__))
                    total_improvement += db_result.performance_improvement
                    all_actions.extend([f"数据库优化: {action}" for action in db_result.actions_taken])
            except Exception as e:
                logger.error(f"Database optimization failed: {e}")
            
            # 等待优化生效
            await asyncio.sleep(5)
            
            # 收集优化后的系统指标
            after_metrics = await self._collect_system_metrics()
            
            # 计算实际性能改善
            actual_improvement = self._calculate_actual_improvement(before_metrics, after_metrics)
            
            execution_time = (time.time() - start_time) * 1000
            
            # 创建优化结果
            result = SystemOptimizationResult(
                optimization_id=optimization_id,
                optimization_type="comprehensive",
                priority=OptimizationPriority.HIGH,
                description="综合系统性能优化",
                performance_improvement=max(total_improvement, actual_improvement),
                resource_savings=self._calculate_resource_savings(before_metrics, after_metrics),
                actions_taken=all_actions,
                before_metrics=before_metrics,
                after_metrics=after_metrics,
                execution_time_ms=execution_time,
                success=True
            )
            
            # 记录优化结果
            self.optimization_history.append(result)
            self._update_optimization_stats(result)
            
            await self.logger.log_performance_optimization(
                "comprehensive_optimization",
                before_metrics,
                after_metrics,
                result.performance_improvement
            )
            
            logger.info(f"Comprehensive optimization completed: {result.performance_improvement:.1f}% improvement")
            
            return result
            
        except Exception as e:
            execution_time = (time.time() - start_time) * 1000
            
            error_result = SystemOptimizationResult(
                optimization_id=optimization_id,
                optimization_type="comprehensive",
                priority=OptimizationPriority.HIGH,
                description="综合系统性能优化失败",
                performance_improvement=0.0,
                resource_savings={},
                actions_taken=[],
                before_metrics={},
                after_metrics={},
                execution_time_ms=execution_time,
                success=False,
                error_message=str(e)
            )
            
            self.optimization_history.append(error_result)
            self._update_optimization_stats(error_result)
            
            await self.logger.log_error("optimization_coordinator", 
                                      f"综合性能优化失败: {str(e)}")
            
            logger.error(f"Comprehensive optimization failed: {e}")
            return error_result
    
    async def _execute_gpu_optimizations(self, suggestions) -> Dict[str, Any]:
        """执行GPU优化建议"""
        try:
            actions_taken = []
            performance_improvement = 0.0
            
            for suggestion in suggestions[:3]:  # 执行前3个建议
                if suggestion.suggestion_type == "pool_rebalancing":
                    success = await self.gpu_manager.rebalance_gpu_pools()
                    if success:
                        actions_taken.append("GPU池重新平衡")
                        performance_improvement += 10.0
                
                elif suggestion.suggestion_type == "memory_defragmentation":
                    # 模拟内存碎片整理
                    actions_taken.append("GPU内存碎片整理")
                    performance_improvement += 8.0
                
                elif suggestion.suggestion_type == "load_balancing_optimization":
                    actions_taken.append("GPU负载均衡优化")
                    performance_improvement += 12.0
            
            return {
                'actions_taken': actions_taken,
                'performance_improvement': performance_improvement,
                'optimization_type': 'gpu_optimization'
            }
            
        except Exception as e:
            logger.error(f"GPU optimization execution failed: {e}")
            return {
                'actions_taken': [],
                'performance_improvement': 0.0,
                'error': str(e)
            }
    
    async def _collect_system_metrics(self) -> Dict[str, Any]:
        """收集系统指标"""
        try:
            # 获取系统状态
            system_status = await self.monitor.get_system_status()
            
            # 获取缓存统计
            cache_stats = await self.cache_manager.get_cache_stats()
            
            # 获取GPU信息
            gpu_info = await self.gpu_manager.get_enhanced_cluster_info()
            
            # 获取数据库性能
            db_report = await self.db_optimizer.get_performance_report()
            
            return {
                'timestamp': datetime.now().isoformat(),
                'system': system_status,
                'cache': cache_stats.get('overall', {}),
                'gpu': gpu_info.get('basic_info', {}),
                'database': db_report.get('summary', {}),
                'health_score': self.system_health_score
            }
            
        except Exception as e:
            logger.error(f"Failed to collect system metrics: {e}")
            return {'error': str(e), 'timestamp': datetime.now().isoformat()}
    
    def _calculate_actual_improvement(self, before_metrics: Dict[str, Any], 
                                    after_metrics: Dict[str, Any]) -> float:
        """计算实际性能改善"""
        try:
            improvements = []
            
            # CPU改善
            before_cpu = before_metrics.get('system', {}).get('cpu_usage', 0)
            after_cpu = after_metrics.get('system', {}).get('cpu_usage', 0)
            if before_cpu > 0:
                cpu_improvement = max(0, (before_cpu - after_cpu) / before_cpu * 100)
                improvements.append(cpu_improvement)
            
            # 内存改善
            before_memory = before_metrics.get('system', {}).get('memory_usage', 0)
            after_memory = after_metrics.get('system', {}).get('memory_usage', 0)
            if before_memory > 0:
                memory_improvement = max(0, (before_memory - after_memory) / before_memory * 100)
                improvements.append(memory_improvement)
            
            # GPU改善
            before_gpu = before_metrics.get('system', {}).get('gpu_usage', 0)
            after_gpu = after_metrics.get('system', {}).get('gpu_usage', 0)
            if before_gpu > 0:
                gpu_improvement = max(0, (before_gpu - after_gpu) / before_gpu * 100)
                improvements.append(gpu_improvement)
            
            # 缓存命中率改善
            before_hit_rate = before_metrics.get('cache', {}).get('hit_rate', 0)
            after_hit_rate = after_metrics.get('cache', {}).get('hit_rate', 0)
            if before_hit_rate > 0:
                cache_improvement = max(0, (after_hit_rate - before_hit_rate) / before_hit_rate * 100)
                improvements.append(cache_improvement)
            
            return statistics.mean(improvements) if improvements else 0.0
            
        except Exception as e:
            logger.error(f"Failed to calculate actual improvement: {e}")
            return 0.0
    
    def _calculate_resource_savings(self, before_metrics: Dict[str, Any], 
                                  after_metrics: Dict[str, Any]) -> Dict[str, Any]:
        """计算资源节省"""
        try:
            savings = {}
            
            # CPU节省
            before_cpu = before_metrics.get('system', {}).get('cpu_usage', 0)
            after_cpu = after_metrics.get('system', {}).get('cpu_usage', 0)
            savings['cpu_reduction_percent'] = max(0, before_cpu - after_cpu)
            
            # 内存节省
            before_memory = before_metrics.get('system', {}).get('memory_usage', 0)
            after_memory = after_metrics.get('system', {}).get('memory_usage', 0)
            savings['memory_reduction_percent'] = max(0, before_memory - after_memory)
            
            # GPU节省
            before_gpu = before_metrics.get('system', {}).get('gpu_usage', 0)
            after_gpu = after_metrics.get('system', {}).get('gpu_usage', 0)
            savings['gpu_reduction_percent'] = max(0, before_gpu - after_gpu)
            
            return savings
            
        except Exception as e:
            logger.error(f"Failed to calculate resource savings: {e}")
            return {}
    
    def _update_optimization_stats(self, result: SystemOptimizationResult):
        """更新优化统计"""
        try:
            self.optimization_stats['total_optimizations'] += 1
            
            if result.success:
                self.optimization_stats['successful_optimizations'] += 1
                self.optimization_stats['total_performance_improvement'] += result.performance_improvement
            else:
                self.optimization_stats['failed_optimizations'] += 1
            
            # 更新平均优化时间
            total_opts = self.optimization_stats['total_optimizations']
            current_avg = self.optimization_stats['avg_optimization_time']
            new_avg = ((current_avg * (total_opts - 1)) + result.execution_time_ms) / total_opts
            self.optimization_stats['avg_optimization_time'] = new_avg
            
            self.optimization_stats['last_optimization_time'] = result.timestamp.isoformat()
            
        except Exception as e:
            logger.error(f"Failed to update optimization stats: {e}")
    
    async def _coordination_loop(self):
        """协调循环"""
        while self.is_running:
            try:
                # 检查是否需要执行优化
                if await self._should_trigger_optimization():
                    # 检查冷却时间
                    time_since_last = (datetime.now() - self.last_optimization_time).total_seconds()
                    
                    if time_since_last >= self.optimization_config['optimization_cooldown_seconds']:
                        await self.execute_comprehensive_optimization()
                        self.last_optimization_time = datetime.now()
                
                await asyncio.sleep(self.optimization_config['optimization_interval_seconds'])
                
            except Exception as e:
                logger.error(f"Error in coordination loop: {e}")
                await asyncio.sleep(60)
    
    async def _health_monitoring_loop(self):
        """健康监控循环"""
        while self.is_running:
            try:
                # 更新系统健康评分
                self.system_health_score = await self._calculate_system_health_score()
                
                # 记录健康状态
                if self.system_health_score < 70:
                    await self.logger.log_warning("optimization_coordinator", 
                                                f"系统健康评分较低: {self.system_health_score:.1f}")
                
                await asyncio.sleep(60)  # 每分钟检查一次
                
            except Exception as e:
                logger.error(f"Error in health monitoring loop: {e}")
                await asyncio.sleep(60)
    
    async def _trend_analysis_loop(self):
        """趋势分析循环"""
        while self.is_running:
            try:
                # 收集性能趋势数据
                await self._update_performance_trends()
                
                # 分析趋势并预测问题
                await self._analyze_performance_trends()
                
                await asyncio.sleep(120)  # 每2分钟分析一次
                
            except Exception as e:
                logger.error(f"Error in trend analysis loop: {e}")
                await asyncio.sleep(120)
    
    async def _should_trigger_optimization(self) -> bool:
        """判断是否应该触发优化"""
        try:
            if not self.optimization_config['auto_optimization_enabled']:
                return False
            
            # 获取当前系统状态
            system_status = await self.monitor.get_system_status()
            
            # 检查临界条件
            cpu_usage = system_status.get('cpu_usage', 0)
            memory_usage = system_status.get('memory_usage', 0)
            gpu_usage = system_status.get('gpu_usage', 0)
            
            critical_threshold = self.optimization_config['critical_threshold']
            
            if (cpu_usage > critical_threshold or 
                memory_usage > critical_threshold or 
                gpu_usage > critical_threshold):
                return True
            
            # 检查健康评分
            if self.system_health_score < 70:
                return True
            
            return False
            
        except Exception as e:
            logger.error(f"Failed to check optimization trigger: {e}")
            return False
    
    async def _calculate_system_health_score(self) -> float:
        """计算系统健康评分"""
        try:
            system_status = await self.monitor.get_system_status()
            
            # 基础分数
            score = 100.0
            
            # CPU评分
            cpu_usage = system_status.get('cpu_usage', 0)
            if cpu_usage > 90:
                score -= 30
            elif cpu_usage > 80:
                score -= 20
            elif cpu_usage > 70:
                score -= 10
            
            # 内存评分
            memory_usage = system_status.get('memory_usage', 0)
            if memory_usage > 90:
                score -= 25
            elif memory_usage > 80:
                score -= 15
            elif memory_usage > 70:
                score -= 8
            
            # GPU评分
            gpu_usage = system_status.get('gpu_usage', 0)
            if gpu_usage > 95:
                score -= 20
            elif gpu_usage > 85:
                score -= 12
            elif gpu_usage > 75:
                score -= 6
            
            # 错误率评分
            if len(self.optimization_history) > 0:
                recent_failures = sum(1 for opt in self.optimization_history[-10:] if not opt.success)
                if recent_failures > 3:
                    score -= 15
                elif recent_failures > 1:
                    score -= 8
            
            return max(0, score)
            
        except Exception as e:
            logger.error(f"Failed to calculate system health score: {e}")
            return 50.0  # 默认中等健康评分
    
    async def _update_performance_trends(self):
        """更新性能趋势"""
        try:
            system_status = await self.monitor.get_system_status()
            
            # 更新趋势数据
            self.performance_trends['cpu_trend'].append(system_status.get('cpu_usage', 0))
            self.performance_trends['memory_trend'].append(system_status.get('memory_usage', 0))
            self.performance_trends['gpu_trend'].append(system_status.get('gpu_usage', 0))
            
            # 保持趋势数据在合理范围内
            for trend_key in self.performance_trends:
                if len(self.performance_trends[trend_key]) > 100:
                    self.performance_trends[trend_key] = self.performance_trends[trend_key][-100:]
            
        except Exception as e:
            logger.error(f"Failed to update performance trends: {e}")
    
    async def _analyze_performance_trends(self):
        """分析性能趋势"""
        try:
            # 分析CPU趋势
            if len(self.performance_trends['cpu_trend']) > 10:
                cpu_trend = self.performance_trends['cpu_trend'][-10:]
                cpu_slope = self._calculate_trend_slope(cpu_trend)
                
                if cpu_slope > 2.0:  # CPU使用率快速上升
                    await self.logger.log_warning("optimization_coordinator", 
                                                 f"CPU使用率快速上升趋势: {cpu_slope:.2f}%/min")
            
            # 分析内存趋势
            if len(self.performance_trends['memory_trend']) > 10:
                memory_trend = self.performance_trends['memory_trend'][-10:]
                memory_slope = self._calculate_trend_slope(memory_trend)
                
                if memory_slope > 1.5:  # 内存使用率上升
                    await self.logger.log_warning("optimization_coordinator", 
                                                 f"内存使用率上升趋势: {memory_slope:.2f}%/min")
            
        except Exception as e:
            logger.error(f"Failed to analyze performance trends: {e}")
    
    def _calculate_trend_slope(self, values: List[float]) -> float:
        """计算趋势斜率"""
        if len(values) < 2:
            return 0.0
        
        n = len(values)
        x = list(range(n))
        
        # 简单线性回归计算斜率
        x_mean = sum(x) / n
        y_mean = sum(values) / n
        
        numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
        denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
        
        if denominator == 0:
            return 0.0
        
        return numerator / denominator
    
    async def get_optimization_report(self) -> Dict[str, Any]:
        """获取优化报告"""
        try:
            recent_optimizations = self.optimization_history[-10:] if self.optimization_history else []
            
            report = {
                'summary': {
                    'system_health_score': self.system_health_score,
                    'total_optimizations': self.optimization_stats['total_optimizations'],
                    'success_rate': (self.optimization_stats['successful_optimizations'] / 
                                   max(self.optimization_stats['total_optimizations'], 1)) * 100,
                    'avg_improvement': (self.optimization_stats['total_performance_improvement'] / 
                                      max(self.optimization_stats['successful_optimizations'], 1)),
                    'avg_optimization_time_ms': self.optimization_stats['avg_optimization_time']
                },
                'recent_optimizations': [
                    {
                        'optimization_id': opt.optimization_id,
                        'type': opt.optimization_type,
                        'improvement': opt.performance_improvement,
                        'actions_count': len(opt.actions_taken),
                        'timestamp': opt.timestamp.isoformat(),
                        'success': opt.success
                    }
                    for opt in recent_optimizations
                ],
                'performance_trends': {
                    key: values[-20:] if len(values) >= 20 else values
                    for key, values in self.performance_trends.items()
                },
                'optimization_config': self.optimization_config,
                'generated_at': datetime.now().isoformat()
            }
            
            return report
            
        except Exception as e:
            logger.error(f"Failed to generate optimization report: {e}")
            return {'error': str(e)}
    
    async def shutdown(self):
        """关闭性能优化协调器"""
        try:
            self.is_running = False
            
            # 停止监控任务
            if self._coordination_task:
                self._coordination_task.cancel()
            if self._health_monitoring_task:
                self._health_monitoring_task.cancel()
            if self._trend_analysis_task:
                self._trend_analysis_task.cancel()
            
            await self.logger.log_info("optimization_coordinator", "性能优化协调器已关闭")
            logger.info("Performance Optimization Coordinator shutdown completed")
            
        except Exception as e:
            logger.error(f"Error during optimization coordinator shutdown: {e}")


# 全局性能优化协调器实例
performance_optimization_coordinator = PerformanceOptimizationCoordinator()